import React, { Component } from "react";
import PropTypes from "prop-types";

import PopoverWithTrigger from "metabase/components/PopoverWithTrigger";

import { normal } from "metabase/lib/colors";

const DEFAULT_COLOR_SQUARE_SIZE = 32;

const ColorSquare = ({ color, size }) =>
    <div style={{
        width: size,
        height: size,
        backgroundColor: color,
        borderRadius: size / 8
    }}></div>

class ColorPicker extends Component {
    static defaultProps = {
        colors: [...Object.values(normal)],
        size: DEFAULT_COLOR_SQUARE_SIZE,
        triggerSize: DEFAULT_COLOR_SQUARE_SIZE,
        padding: 4
    }

    static propTypes = {
        colors: PropTypes.array,
        onChange: PropTypes.func.isRequired,
        size: PropTypes.number,
        triggerSize: PropTypes.number,
        value: PropTypes.string
    }

    render () {
        const { colors, onChange, padding, size, triggerSize, value } = this.props;
        return (
            <div className="inline-block">
                <PopoverWithTrigger
                    ref="colorPopover"
                    triggerElement={
                        <div
                            className="bordered rounded flex align-center"
                            style={{ padding: triggerSize / 4 }}
                        >
                            <ColorSquare color={value} size={triggerSize} />
                        </div>
                    }
                >
                    <div className="p1">
                        <ol
                            className="flex flex-wrap"
                            style={{
                                maxWidth: 120
                            }}
                        >
                            { colors.map((color, index) =>
                                <li
                                    className="cursor-pointer"
                                    style={{ padding }}
                                    key={index}
                                    onClick={() => {
                                        onChange(color);
                                        this.refs.colorPopover.close();
                                    }}
                                >
                                    <ColorSquare color={color} size={size} />
                                </li>
                            )}
                        </ol>
                    </div>
                </PopoverWithTrigger>
            </div>
        );
    }
}

export default ColorPicker;
